package com.xkdx.guangguang.fragment.my.pay;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.shopunitproduct.OrderProductInfoFragment;
import com.xkdx.guangguang.fragment.shopunitproduct.UnitProductInfoFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.ProductInfo;
import com.xkdx.guangguang.util.DialogFactory;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class PayByPosFragment extends BaseFragment implements OnClickListener,
		TCPSocketCallback {

	private static final String TAG = "PayByPosFragment";
	private View view;
	private Button back;
	private EditText ed_ip, ed_show;
	private ImageView im_commit;

	private TCPSocketConnect connect = null;
	private String resultShow;
	private static final int TYPE_PAY = 1;
	private static final int TYPE_QUERY = 2;
	private String amt;
	private String trace;
	private String oldTrace;
	private String objectMessage;
	private String message;
	private int selectPos = 0;
	private Dialog dialog;
	private SharePrefenceUtil sp;
	private String pos_ip;

	private PayPosBackAction payPosBackAction;
	private PayPosBackModule payPosBackModule;
	private PayPosBackPresistence payPosBackPresistence;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sp = new SharePrefenceUtil(getActivity(), IConstants.SP_POS);
		pos_ip = sp.getPosIP();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.pos_zf, container, false);
		findViews(view);
		return view;
	}

	private void findViews(View view) {
		ed_ip = (EditText) view.findViewById(R.id.ed_pos_ip);
		ed_show = (EditText) view.findViewById(R.id.ed_pos_result);
		if (TextUtils.isEmpty(pos_ip)) {
			ed_ip.setHint(getResources().getString(R.string.input_ip));
		} else {
			ed_ip.setText(pos_ip);
		}
		ed_ip.setText(pos_ip);
		im_commit = (ImageView) view.findViewById(R.id.im_pos_zf);
		back = (Button) view.findViewById(R.id.ed_pos_back);
		im_commit.setOnClickListener(this);
		back.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ed_pos_back: // 返回按钮

			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			break;

		case R.id.im_pos_zf:
			if (!isIPAvilidate()) {
				return;
			} else {
				dialog = DialogFactory.creatRequestDialog(getActivity(),
						"正在连接通信,请耐心等待...");
				dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
				dialog.show();
				IConstants.POS_ADDRESS = ed_ip.getText().toString();
				PosRequest();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 判断提交按钮相关是否合法
	 * 
	 * @return true合法 , false不合法
	 */
	private boolean isIPAvilidate() {

		String ip = ed_ip.getText().toString().trim();
		if (TextUtils.isEmpty(ip)) {
			ed_ip.setFocusable(true);
			ed_ip.setFocusableInTouchMode(true);
			ed_ip.requestFocus();
			Toast.makeText(getActivity(), "POS机IP地址不能为空...", Toast.LENGTH_SHORT)
					.show();
			return false;
		} else if (!(ipCheck(ip))) {
			ed_ip.setFocusable(true);
			ed_ip.setFocusableInTouchMode(true);
			ed_ip.requestFocus();
			Toast.makeText(getActivity(), "输入的IP地址格式不正确,请重新输入", 0).show();
			return false;

		}
		return true;
	}

	/**
	 * 验证ip是否合法
	 * 
	 * @param text
	 *            ip地址
	 * @return 验证信息
	 */
	public boolean ipCheck(String text) {

		// 定义正则表达式
		String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
				+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
				+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
				+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
		// 判断ip地址是否与正则表达式匹配
		if (text.matches(regex)) {
			// 返回判断信息
			return true;
		} else {
			// 返回判断信息
			return false;
		}

	}

	/**
	 * pos机支付
	 */
	private void PosRequest() {
		connect = new TCPSocketConnect(this);

		connect.setAddress(IConstants.POS_ADDRESS, IConstants.POS_PORT);
		new Thread(connect).start();
	}

	@Override
	public void findView() {
	}

	@Override
	public void setOnClick() {
	}

	@Override
	public void showLoading() {
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
	}

	protected String sendRequest(int type) {
		String mainBody = new String();

		if (type == TYPE_PAY) {
			String amt = String
					.valueOf((int) (Integer.parseInt(IConstants.ProductStatic
							.getProductTotalPrice())));
			String trace = IConstants.ProductStatic.getProductPosTrace();

			ArrayList<ProductInfo> proList = new ArrayList<ProductInfo>();
			proList.add(IConstants.ProductStatic);
			mainBody = CreatePayRequest("PAY", amt, trace, proList);

		} else {
			String amt = String
					.valueOf((int) (Integer.parseInt(IConstants.ProductStatic
							.getProductTotalPrice())));
			String trace = IConstants.ProductStatic.getProductPosTrace();
			String oldString = "";

			mainBody = CreateQueryRequest("QUERY", amt, trace, oldString);
		}

		return mainBody.toString();
	}

	protected void JsonParse(final String resultShow2) {

		new Thread() {
			public void run() {
				JSONObject obj;
				try {

					int pos = resultShow2.indexOf("{");
					String finalResult = resultShow2.substring(pos);
					obj = new JSONObject(finalResult);
					String code = obj.getString("rescode");
					if (!(code.equals("00"))) {

						// PayFragment.isBack = false;

						handler.sendEmptyMessage(5);

					} else {

						handler.sendEmptyMessage(6);

					}
				} catch (JSONException e) {

					handler.sendEmptyMessage(5);

				}
			};
		}.start();

	}

	/**
	 * 十进制到十六进制转换,并转换成\X形式
	 * 
	 * @param queryLength
	 */
	protected String TentoSixteen(int queryLength) {
		if (queryLength > 0) {
			String result = Integer.toHexString(queryLength);
			String msg;
			int len = result.length();
			StringBuffer sb = null;

			while (len < 4) {
				sb = new StringBuffer();
				sb.append("0").append(result);// 左(前)补0
				result = sb.toString();
				len = result.length();
			}

			return result;
		} else {
			return "0000";
		}
	}

	/**
	 * 生成支付接口对应的字符串
	 * 
	 * @param type
	 *            “PAY”
	 * @param amt2
	 *            总价格
	 * @param trace2
	 *            流水号
	 * @param ArrayList
	 *            <ProductInfo> 商品信息
	 */
	private String CreatePayRequest(String type, String amt, String trace,
			ArrayList<ProductInfo> proList) {
		int productAmount = proList.size();
		StringBuffer prosb = new StringBuffer();
		if (productAmount > 0) {

			prosb.append(productAmount).append("|");
			for (int i = 0; i < productAmount; i++) {

				ProductInfo info = proList.get(i);
				String productName = info.getProductName();
				String productId = info.getProductID();
				String productUnitPrice = info.getProductPrice();
				String productNum = info.getOrder_Num();
				String ProductTotalPrice = String.valueOf(Integer
						.parseInt(productUnitPrice)
						* Integer.parseInt(productNum));
				float unitPrice = Float.parseFloat(productUnitPrice) / 100;

				float totalPrice = Float.parseFloat(ProductTotalPrice) / 100;

				DecimalFormat decimalFormat = new DecimalFormat(".00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
				String unitPriceStr = decimalFormat.format(unitPrice);// format
																		// 返回的是字符串

				String totalPriceStr = decimalFormat.format(totalPrice);// format
																		// 返回的是字符串
				prosb.append(productName + "," + productId + "," + productNum
						+ "," + unitPriceStr + "," + totalPriceStr + ",|");

			}
		}
		StringBuffer sbuff = new StringBuffer();
		sbuff.append("{\"cmd\":\"");
		sbuff.append(type).append("\",\"amt\":\"").append(amt)
				.append("\",\"trace\":\"").append(trace)
				.append("\",\"detail\":\"").append(prosb);
		sbuff.append("\"}");
		return sbuff.toString();

	}

	/**
	 * 查询接口
	 * 
	 * @param type
	 *            "Query"
	 * @param amt
	 *            总价格
	 * @param trace
	 *            流水号
	 * @param oldtrace
	 *            原流水号
	 */
	private String CreateQueryRequest(String type, String amt, String trace,
			String oldtrace) {
		StringBuffer sbuff = new StringBuffer();
		sbuff.append("{\"");
		sbuff.append(type).append("\",\"").append(amt).append("\",\"")
				.append(trace).append("\",\"").append(oldtrace);
		sbuff.append("\"}");
		return sbuff.toString();

	}

	@Override
	public void tcp_connected() {
		handler.sendEmptyMessage(1);
	}

	@Override
	public void tcp_receive(String result) {
		try {

			resultShow = result;

		} catch (Exception e) {
			e.printStackTrace();
		}

		handler.sendEmptyMessage(2);
	}

	@Override
	public void tcp_disconnect() {
		handler.sendEmptyMessage(3);
	}

	@Override
	public void tcp_closeconnect() {
		handler.sendEmptyMessage(4);
	}

	public void showPosBackLoaded(HashMap<String, AbsModule> map) {
		// if (dialog != null && dialog.isShowing()) {
		// dialog.dismiss();
		// }
		if (map.containsKey("0")) {
			// Toast.makeText(getActivity(), payPosBackModule.message,
			// 0).show();
			Log.i(TAG, payPosBackModule.message);
		} else {
			Log.i(TAG, payPosBackModule.message);
		}
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				sp.setPosIP(IConstants.POS_ADDRESS);
				if (getActivity() != null) {
					Toast.makeText(getActivity(), "连接成功!", 0).show();
				}
				// **
				// * 支付接口
				// **/
				String bodyStr = sendRequest(TYPE_PAY); // 消息体

				// 方法1根据中文获取长度
				// int qmLength = bodyStr.length()
				// +IConstants.ConutHanZi(bodyStr);

				// 方法2,将中文字符串转为gbk形式，获取字节数
				int qmLength = 0;
				try {
					qmLength = bodyStr.getBytes("gbk").length;
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				String headqmMessage = TentoSixteen(qmLength); // 对应消息头
				byte[] head_byte = new byte[2]; // 对应消息头字节数 固定为2
				head_byte = IConstants.hexStringToBytes(headqmMessage);
				connect.write(head_byte); // 发送
				connect.writeBody(bodyStr); // 发送
				connect.writeBody("\r\n");
				break;
			case 2:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}

				/**
				 * 解析返回数据
				 */
				JsonParse(resultShow);

				break;

			case 3:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				if (getActivity() != null) {
					Toast.makeText(getActivity(), "pos连接失败，请检查网络连接,重新支付!", 0)
							.show();
				}
				break;

			case 4:
				// if (dialog != null && dialog.isShowing()) {
				// dialog.dismiss();
				// }
				Log.i("pay", "关闭连接");
				break;

			case 5:

				PayFragment.isBack = false;
				OrderProductInfoFragment.isOrderBack = false;
				UnitProductInfoFragment.isUnitBack = false;

				if (getActivity() != null) {
					dialog = DialogFactory.creatRequestDialog(getActivity(),
							"支付失败，请重新支付");
					dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
					DialogFactory.setBtnVisable(View.VISIBLE);
					DialogFactory.setBtnMessage("重新支付");
					DialogFactory.setClick(new OnClickListener() {

						@Override
						public void onClick(View v) {

							dialog.dismiss();

						}
					});
					dialog.show();
				}
				break;
			case 6:

				if (getActivity() != null) {

					dialog = DialogFactory.creatRequestDialog(getActivity(),
							"支付成功，请收好交易凭条");
					dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
					DialogFactory.setBtnVisable(View.VISIBLE);
					DialogFactory.setBtnMessage("继续购物");
					DialogFactory.setClick(new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
							PayFragment.isBack = true;
							OrderProductInfoFragment.isOrderBack = true;
							UnitProductInfoFragment.isUnitBack = true;
							getFragmentManager().popBackStack();
						}
					});
					dialog.show();
				}

				String id = IConstants.ProductStatic.getProductID();
				String num = IConstants.ProductStatic.getOrder_Num();
				String totalPrice = IConstants.ProductStatic
						.getProductTotalPrice();
				String trace = IConstants.ProductStatic.getProductPosTrace();
				payPosBackAction = new PayPosBackAction(id, num, totalPrice,
						trace);
				payPosBackModule = new PayPosBackModule();
				payPosBackPresistence = new PayPosBackPresistence(
						PayByPosFragment.this);
				((ManagerActivity) getActivity())
						.addCurrentTask(payPosBackPresistence);
				payPosBackPresistence.setActitons(payPosBackAction);
				payPosBackPresistence.setModule(payPosBackModule);
				payPosBackPresistence.execute();

				break;
			}
		}
	};

}
